import {
  Shader,
  ShaderData,
  ShaderProperty,
  ShaderPool,
  ShaderProgram,
  ShaderProgramPool,
  ShaderMacro,
  ShaderMacroCollection,
  ShaderDataGroup,
  ShaderLib
} from "@nirvana/shaders";

import { WebGLCanvas } from "@nirvana/canvas";
import { IndexBufferData, VertexBufferData, DataElement } from "@nirvana/core";
// 使用使用 Canvas
let canvas = document.getElementById("engine-nirvana");


const webCanvas = new WebGLCanvas(canvas, {
  // fullScreen: true, // 自动放大全屏
  // fixWidth: 500, // 放大
  // auto: true // 页面设置了canvas 样式
  // 2d: true,
});
// webCanvas.fullScreen();
const engine = webCanvas.engine;
const gl = engine.gl;
const pool1: ShaderProgramPool = new ShaderProgramPool();

const planeVS = `
attribute vec3 aVertexPosition;
void main() {
  gl_Position = vec4(aVertexPosition, 1.0);
}
`;
const planeFS = `
void main() {
  gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
`;

const plane = Shader.create("plane", planeVS, planeFS);
console.log(plane, Shader.find("plane"));
const pool3: ShaderProgramPool = new ShaderProgramPool();
const shaderMacroCollection: ShaderMacroCollection = new ShaderMacroCollection();
console.log(shaderMacroCollection);
const planeProgram: ShaderProgram = plane.getShaderProgram(engine.gl, shaderMacroCollection, pool3);
console.log("plane", planeProgram);

let indices = [0, 1, 2, 2, 1, 3]; //
var vertices = [-0.5, 0.5, 0, -0.5, -0.5, 0, 0.5, 0.5, 0, 0.5, -0.5, 0]; //

let nIndices: number[] = [];
if (indices && indices.length > 0) {
  for (let i = 0, len = indices.length; i < len; i += 3) {
    const a = indices[i + 0];
    const b = indices[i + 1];
    const c = indices[i + 2];

    nIndices.push(a, b, b, c, c, a);
  }
} else {
  for (let i = 0, l = vertices.length / 3 - 1; i < l; i += 3) {
    const a = i + 0;
    const b = i + 1;
    const c = i + 2;

    nIndices.push(a, b, b, c, c, a);
  }
}

const vBuffer = new VertexBufferData(new Float32Array(vertices), [
  new DataElement("aVertexPosition", 3, gl.FLOAT, false, 0, 0)
]);
const iBuffer = new IndexBufferData(new Uint16Array(nIndices));
vBuffer.create(gl);
iBuffer.create(gl);

const planeShaderData: ShaderData = new ShaderData(ShaderDataGroup.Material);
console.log(ShaderDataGroup, planeShaderData);

engine.update = (gl) => {
  // console.log('--');
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  // 用上面指定的颜色清除缓冲区
  gl.clear(gl.COLOR_BUFFER_BIT);
  // 面start 二
  planeProgram.bind();
  // gl.vertexAttribPointer(aVertexPosition, 2, gl.FLOAT, false, 0, 0);
  // gl.enableVertexAttribArray(aVertexPosition);
  // gl.drawArrays(gl.TRIANGLES, 0, 4);
  // 面end
  vBuffer.upload(planeProgram._glProgram, gl);
  iBuffer.upload(gl);
  gl.drawElements(gl.LINES, nIndices.length, gl.UNSIGNED_SHORT, 0);
};
